package com.c5p1ng.route.util;

import com.c5p1ng.route.context.GlobalContext;
import org.slf4j.MDC;

/**
 * 上下文工具类
 *
 * @author csp
 */
public class ContextUtil {
    public static final String REQUEST_CONTEXT = "request-context";
    public static final String TRACE_ID = "PtxId";

    public static ThreadLocal<GlobalContext> currentThreadLocal = ThreadLocal.withInitial(() -> new GlobalContext());

    public ContextUtil() {
    }

    public static GlobalContext getCurrentContext() {
        return currentThreadLocal.get();
    }

    public static void setCurrentContext(GlobalContext globalContext) {
        currentThreadLocal.set(globalContext);
        String traceId = globalContext.getTraceId();
        if (traceId != null && traceId.length() > 0 && MDC.get("PtxId") == null) {
            MDC.put("PtxId", traceId);
        }

    }

    public static void clear() {
        MDC.clear();
        currentThreadLocal.remove();
    }

    public static void setTranceId(String traceId) {
        MDC.put("PtxId", traceId);
        getCurrentContext().setTraceId(traceId);
    }

    public static String getTraceId() {
        return MDC.get("PtxId");
    }
}
